<template>
  <el-card class="box-card">
    <div slot="header" class="clearfix">
      <el-form :inline="true" :model="formInline" class="demo-form-inline">
        <el-form-item label="角色名称">
          <el-input
            v-model="formInline.name"
            placeholder="请输入角色名称"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <div class="gauge">
            <el-button type="primary" @click="onSubmit">查询</el-button>
            <el-button type="primary" @click="onReset">重置</el-button>
            <el-button type="primary" @click="onNewly">新增角色</el-button>
          </div>
        </el-form-item>
      </el-form>
    </div>
    <div class="text item">
      <el-table
        v-loading="loading"
        :data="tableData"
        border
        style="width: 100%"
        max-height="600"
      >
        <el-table-column
          type="index"
          align="center"
          label="序号"
          :index="indexMethod"
          width="60"
        >
        </el-table-column>
        <el-table-column prop="name" align="center" label="角色名称">
        </el-table-column>
        <el-table-column
          prop="limits_name"
          align="center"
          label="菜单权限"
          show-overflow-tooltip
        >
          <!-- <template slot-scope="scope">
            {{ scope.row.role.name }}
          </template> -->
        </el-table-column>
        <el-table-column label="操作" align="center" width="330">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="primary"
              @click="handleEdit(scope.row)"
              class="handList"
              >编辑</el-button
            >
            <el-button
              size="mini"
              type="danger"
              @click="handleDelete(scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="page"
        :page-sizes="[10, 100, 200, 300]"
        :page-size="10"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </div>
    <el-dialog
      :visible.sync="dialogVisible"
      width="35%"
      :before-close="handleClose"
    >
      <el-form
        ref="form"
        :rules="rules"
        :model="formLabelAlign"
        label-width="80px"
      >
        <div class="formUser">
          <el-form-item label="角色名称" prop="name">
            <el-input
              v-model="formLabelAlign.name"
              placeholder="请输入角色名称"
            ></el-input>
          </el-form-item>
        </div>
        <!-- <div class="formUser">
          <el-form-item label="密码" prop="password">
            <el-input
              v-model="formLabelAlign.password"
              placeholder="请输入密码"
            ></el-input>
          </el-form-item>
        </div> -->
        <el-form-item label="选择菜单" prop="limits_id">
          <!-- <el-select
            v-model="formLabelAlign.role_id"
            multiple
            clearable
            placeholder="请选择菜单"
          >
            <el-option
              v-for="item in options1"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select> -->
          <el-cascader
            v-model="formLabelAlign.limits_id"
            :options="options1"
            collapse-tags
            :props="{
              multiple: true,
              value: 'id',
              label: 'name',
              children: 'son',
            }"
          ></el-cascader>
        </el-form-item>
        <!-- <el-form-item label="店铺名称">
          <el-select v-model="form.status" placeholder="请选择">
            <el-option
              v-for="item in options1"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item> -->
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="save">确 定</el-button>
      </span>
    </el-dialog>
  </el-card>
</template>

<script>
import {
  getHardwareRole,
  addHardwareRole,
  editHardwareRole,
  delHardwareRole,
  getMainRoleMenu,
} from "../../../../utils/main";
export default {
  data() {
    return {
      //弹窗
      dialogVisible: false,
      loading: false,
      token: sessionStorage.getItem("token"),
      formInline: {
        name: "",
      },
      options1: [],
      tableData: [],
      //新增
      formLabelAlign: {
        name: "",
        password: "",
        password: "",
      },
      //分页器
      total: 0,
      limit: 10,
      page: 1,
      currentPage: 1,
      seller_id: sessionStorage.getItem("seller_id"),
      // seller_id: 8,
      name: "",
      limits_id: "",
      //校验
      rules: {
        name: [{ required: true, message: "请输入角色名称", trigger: "blur" }],
        limits_id: [{ required: true, message: "请选择角色", trigger: "blur" }],
      },
    };
  },
  methods: {
    //每页多少条
    handleSizeChange(val) {
      this.limit = val;
      this.getList();
    },
    //第几页
    handleCurrentChange(val) {
      this.page = val;
      this.getList();
    },
    //查询
    onSubmit() {
      this.name = this.formInline.name;
      this.page = 1;
      this.getList();
    },
    //重置
    onReset() {
      this.name = "";
      this.formInline.name = "";
      this.getList();
      // console.log("重置");
    },
    //新增账号
    onNewly() {
      this.dialogVisible = true;
      this.formLabelAlign = {};
      // this.formLabelAlign.seller_name = "";
      // this.formLabelAlign.role_id = "";
      // this.formLabelAlign.password = "";
    },
    //编辑
    handleEdit(row) {
      this.dialogVisible = true;
      let obj = JSON.parse(JSON.stringify(row));
      this.formLabelAlign = obj;
      this.formLabelAlign.limits_id = JSON.parse(obj.limits_data);
      // console.log(row.limits_id);
      // let list = obj.limits_id.split(",");
      // // console.log(list, 111);
      // for (let i = 0; i < list.length; i++) {
      //   list[i] = Number(list[i]);
      // }
      // // console.log(list, 222);
      // this.formLabelAlign.limits_id = list;
      // console.log(this.formLabelAlign, 1111);
      // this.formLabelAlign.role_id = row.role.name;
    },
    async getList() {
      this.loading = true;
      let res = await getHardwareRole(
        this.token,
        this.name,
        this.seller_id,
        this.page,
        this.limit,
        4
      );
      if (res.data.status) {
        this.tableData = res.data.data.data || [];
        this.total = res.data.data.count;
        // console.log(this.tableData.list, "55555");
        let timer = setTimeout(() => {
          this.loading = false;
          clearTimeout(timer);
        }, 400);
      } else {
        if (res.data.msg == "token失效,请重新进行登录") {
          this.$router.push("/materilsLogin");
        }
        if (res.data.msg == "此账号没有权限") {
          this.$message.error(res.data.msg);
          this.loading = false;
        }
        let timer = setTimeout(() => {
          this.$message.error(res.data.msg);
        }, 5000);
      }
    },
    formatData(data) {
      for (var i = 0; i < data.length; i++) {
        if (data[i].son == null || data[i].son.length == 0) {
          data[i].son = undefined;
        } else if (data[i].son.length >= 1) {
          this.formatData(data[i].son);
        }
      }
      return data;
    },
    async getSelect() {
      // this.loading = true;
      let res = await getMainRoleMenu(this.token, "五金店")
        .then((res) => {
          // console.log(this.type, 88888);
          if (res.data.status) {
            this.options1.push(res.data.data);
            this.options1 = this.formatData(this.options1);
            // console.log(this.options1);
            // this.total = res.data.data.count;
            // console.log(111, this.options);
            // let timer = setTimeout(() => {
            //   this.loading = false;
            //   clearTimeout(timer);
            // }, 400);
          } else {
            if (res.data.msg == "token失效,请重新进行登录") {
              this.$router.push("/materilsLogin");
            }
            if (res.data.msg == "此账号没有权限") {
              this.$message.error(res.data.msg);
              this.loading = false;
            }
            // let timer = setTimeout(() => {
            //   this.$message.error(res.data.msg);
            // }, 5000);
          }
        })
        .catch((err) => {
          console.log(err.message);
        });
    },
    // 序号排序
    indexMethod(index) {
      if (this.total < this.limit) {
        return this.total - index;
      } else {
        return this.total - (this.page - 1) * this.limit - index;
      }
    },

    //删除
    handleDelete(row) {
      this.$confirm("此操作将永久删除该员工, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          console.log(row.id);
          delHardwareRole(this.token, row.id).then((res) => {
            if (res.data.status) {
              this.$message({
                type: "success",
                message: "删除成功",
              });
              this.getList();
            } else {
              this.$message.error(res.data.msg);
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    //关闭
    handleClose(done) {
      this.$refs.form.resetFields();
      done();
      // this.empty();
    },
    //取消
    cancel() {
      this.dialogVisible = false;
      this.$refs.form.resetFields();
      // this.empty();
    },
    //弹出框的确定按钮
    save() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.formLabelAlign.id != null) {
            // 编辑
            editHardwareRole(
              this.token,
              this.formLabelAlign.id,
              this.formLabelAlign.name,
              this.formLabelAlign.limits_id,
              JSON.stringify(this.formLabelAlign.limits_id),
              4
            ).then((res) => {
              if (res.data.status == true) {
                this.$message({
                  message: "修改成功",
                });
                this.dialogVisible = false;
                this.getList();
              } else {
                this.$message.error(res.data.msg);
              }
            });
          } else {
            addHardwareRole(
              this.token,
              this.seller_id,
              this.formLabelAlign.name,
              this.formLabelAlign.limits_id,
              JSON.stringify(this.formLabelAlign.limits_id),
              4
            ).then((res) => {
              if (res.data.status == true) {
                this.$message({
                  message: "新增成功",
                });
                this.total = res.data.data.count;
                this.formLabelAlign = {};
                this.dialogVisible = false;
                this.getList();
              } else {
                this.$message.error(res.data.msg);
              }
            });
          }
        } else {
          return false;
        }
      });
    },
  },
  mounted() {
    this.getList();
    this.getSelect();
  },
};
</script>

<style scoped>
.text {
  font-size: 14px;
}

.item {
  margin-bottom: 18px;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}

.clearfix:after {
  clear: both;
}

.box-card {
  width: 100%;
}

.gauge {
  display: flex;
  margin: 0 20%;
}

.oneLine {
  display: flex;
  justify-content: space-between;
  margin-bottom: 14px;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.formUser {
  width: 80%;
}
.itemUser {
  margin-bottom: 20px;
}
</style>